package com.gpy.exportmultiexceltozip.controller;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
@RequestMapping(value = "/exportExcelZip")
public class PoiZip {

    //文件全路径名
    String diskFilePath = "c:/temp/";

    private Logger log = LoggerFactory.getLogger(this.getClass());

    //测试  http://localhost:8080/admin/test/test/poizip
    @RequestMapping(value = "/exportToChrome")
    public void poizip(HttpServletResponse response) throws IOException {
        List<Workbook> wbs=createWorkbooks();
        //response 输出流
        ServletOutputStream out = response.getOutputStream();
        //压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(out);
        try {
            for (int i = 0; i < wbs.size(); i++) {
                Workbook wb=wbs.get(i);
                response.setContentType("application/octet-stream; charset=utf-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("测试.zip", "utf-8") );
                //重点开始,创建压缩文件
                ZipEntry z = new ZipEntry(i + ".xls");
                zipOutputStream.putNextEntry(z);
                //写入一个压缩文件
                wb.write(zipOutputStream);
            }
            zipOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //注意关闭顺序，否则可能文件错误
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    @RequestMapping(value = "/exportFromDisk")
    public void exportExcel(HttpServletRequest resq, HttpServletResponse response) throws IOException {
        List<Workbook> wbs=createWorkbooks();
        Map<String, Workbook> wbMap=new HashMap<>();
        for (int i = 0; i < wbs.size(); i++) {
            wbMap.put(i+"",wbs.get(i));
        }
        String fileName=exportWBSToZipToDisk(wbMap);
        try {
            // path是指想要下载的文件的路径
            File file = new File(fileName);
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode( "测试." + ext, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            log.info("excel压缩包生成异常");
            log.error("Exception:", ex);
        }
    }

    /**
     * @param wbMap
     * @description: 将多个workbook导出为包含多个excel的压缩包并保存到磁盘
     * @return: java.lang.String 文件名
     * @author gpy
     * @date: 2021-5-11 9:50
     */
    private String exportWBSToZipToDisk(Map<String, Workbook> wbMap) throws IOException {
        //response 输出流
        String fileName = UUID.randomUUID() + ".zip";
        File filePath = new File(diskFilePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        File fullPath = new File(filePath + fileName);
        FileOutputStream out = new FileOutputStream(fullPath);
        //压缩输出流
        ZipOutputStream outputStream = new ZipOutputStream(out);
        //压缩输出流
        //OutputStream outputStream = new FileOutputStream(out);
        try {
            for (String key : wbMap.keySet()) {
                //开始,创建压缩文件
                ZipEntry z = new ZipEntry(key + ".xls");
                outputStream.putNextEntry(z);
                //写入一个压缩文件
                wbMap.get(key).write(outputStream);
            }
            outputStream.flush();
        } catch (Exception e) {
            log.error("报告文件生成异常", e);
            throw e;
        } finally {
            //注意关闭顺序，否则可能文件错误
            if (outputStream != null) {
                outputStream.close();
            }
            if (out != null) {
                out.close();
            }
        }
        log.info("报告文件已生成,路径为:" + diskFilePath + fileName);
        return fileName;
    }

    public List<Workbook> createWorkbooks(){
        List<Workbook> wbs=new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            //创建工作簿
            Workbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("sheet" + i);
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue("内容" + i);
            wbs.add(wb);
        }
        return wbs;
    }
}
